import pymysql
import pytest
from uuid import uuid4
import random
import requests
import time

DB_CONFIG = {
    'host':'localhost',
    'user':'root',
    'password':'cpy50686868cpy',
    'db':'Prac'
}

#数据工厂，产生测试数据
def generate_test_data():

    usrid =  f'test_user_{uuid4().hex[:8]}'
    product_id = random.randint(1000,9999)

    return {
        'username':usrid,
        'password':'123123',
        'product_id':product_id,
        'price':round(random.uniform(10,100),2),
        'quantity':random.randint(1,5)
    }

@pytest.fixture(scope='module')
def db_connection():
    connnection = pymysql.connect(**DB_CONFIG)
    yield connnection
    connnection.close()



@pytest.fixture
def test_user(db_connection):
    test_data = generate_test_data()
    print(test_data)

    with db_connection.cursor() as c:
        rows = c.execute('insert into user1 (id,username,password1) values (%s,%s,%s)',(1,test_data['username'],test_data['password']))
        print(f'成功插入{rows}条数据')
        db_connection.commit()

    yield test_data

    with db_connection.cursor() as c:
        rows = c.execute('delete from user1 where username = %s',(test_data['username'],))
        print(f'成功删除{rows}条数据')
        db_connection.commit()


@pytest.fixture
def jwt(test_user):

    #模拟调用登录接口，获取jwt
    res = requests.post(
        'http://127.0.0.1:8082/post',
        params={'username':test_user['username'],'password':test_user['password']},
        headers={'athuor':'caipeiyan'},
        json={'des':'这个一个post请求','jwt':'2fjldsaj2'}
        )
    res_json = res.json()
    jwt_in_use = res_json['json']['jwt']
    jwt_token = {'Authorization':f'Bearer {jwt_in_use}'}
    return jwt_token

@pytest.fixture
def create_product(db_connection,test_user):
    product_id = test_user['product_id']
    price = test_user['price']
    quantity = test_user['quantity']
    print(f'商品数据创建为为{product_id},{price},{quantity}')
    with db_connection.cursor() as c:
        rows = c.execute('insert into product (id,price,quantity) values (%s,%s,%s)',(product_id,price,quantity))
        print(f'成功插入{rows}条商品')
        db_connection.commit()
    yield rows

    with db_connection.cursor() as c:
        rows = c.execute('delete from product where id = %s',(product_id,))
        print(f'成功删除{rows}条数据')
        db_connection.commit()


#正式的办理业务
def test_all1(db_connection,test_user,jwt,create_product):
    #第一步：使用jwt办理业务
    res = requests.get('http://127.0.0.1:8082/bearer',headers=jwt)
    print(f'业务办理数据返回为{res.text}')

    time.sleep(20)
    assert res.status_code == 200

    

